﻿using System.Windows;
using System.Windows.Media;
using Socium.Domain.Documents;
using Socium.Presentation;

namespace Socium.Documents.Sociograms {
	class RelationViewModel : ViewModelBase {
		public RelationViewModel(SociogramRelation relation, RelationGroupViewModel relation_group, NodeViewModel elector, NodeViewModel elected) {
			//_relation = relation;
			_relation_group = relation_group;
			_elector_view_model = elector;
			_elected_view_model = elected;

			UpdateElector();
			UpdateElected();

			elector.LayoutChanged += ElectorViewModelLayoutChanged;
			elected.LayoutChanged += ElectedViewModelLayoutChanged;
		}

		//SociogramRelation _relation;

		readonly RelationGroupViewModel _relation_group;
		readonly NodeViewModel _elector_view_model;
		readonly NodeViewModel _elected_view_model;

		public Brush Brush {
			get { return RelationGroup.Brush; }
		}

		double _x1;
		double _y1;

		double _x2;
		double _y2;

		public double X1 {
			get { return _x1; }
			set {
				_x1 = value;
				OnPropertyChanged("X1");
			}
		}

		public double Y1 {
			get { return _y1; }
			set {
				_y1 = value;
				OnPropertyChanged("Y1");
			}
		}

		public double X2 {
			get { return _x2; }
			set {
				_x2 = value;
				OnPropertyChanged("X2");
			}
		}

		public double Y2 {
			get { return _y2; }
			set {
				_y2 = value;
				OnPropertyChanged("Y2");
			}
		}

		public RelationGroupViewModel RelationGroup {
			get { return _relation_group; }
		}

		public NodeViewModel Elector {
			get { return _elector_view_model; }
		}

		void ElectorViewModelLayoutChanged(object sender, System.EventArgs e) {
			UpdateElector();
		}

		void ElectedViewModelLayoutChanged(object sender, System.EventArgs e) {
			UpdateElected();
		}

		Point GetLocation(NodeViewModel view_model) {
			var x = view_model.Left + view_model.Width / 2d;
			var y = view_model.Top + view_model.Height / 2d;

			return new Point(x, y);
		}

		void UpdateElector() {
			var location = GetLocation(Elector);
			X1 = location.X;
			Y1 = location.Y;
		}

		void UpdateElected() {
			var location = GetLocation(_elected_view_model);
			X2 = location.X;
			Y2 = location.Y;
		}
	}
}
